#include <stdio.h>
#include <stdlib.h>
#include <math.h>

typedef struct{ 
	int unbits;    //bits não lidos, estão "flutuando"
	int quant;     //quantidade de bits não lidos
}unread;

int get_bit(FILE *fl, unread *a, int b)
{
	int i,vezes,resto,mask=0;
	int read_bits=0;
	if(a->quant==0 || b-(a->quant)>0)
	{
		resto=b%8;
		vezes=b/8;
		if((a->quant)>0)
		{
			resto=(b-(a->quant))%8;
			vezes=(b-(a->quant))/8;
			read_bits=(a->unbits)<<8*vezes;
		}
		if(resto>0)
		{
			for(i=0;i<vezes;i++) read_bits=read_bits+(getc(fl)<<((vezes-i-1)*8));
			read_bits=read_bits<<resto;
			for(i=0;i<resto;i++) mask=(mask<<1)+1;
			mask=mask<<8-resto;
			a->unbits=getc(fl);
			read_bits=read_bits+(((a->unbits)&mask)>>(8-resto));
			mask=0;
			for(i=0;i<8-resto;i++)mask=(mask<<1)+1;
			a->unbits=(a->unbits)&mask;
			a->quant=8-resto;
		}
		else
		{
			for(i=0;i<vezes;i++) read_bits=read_bits+(getc(fl)<<((vezes-i-1)*8));
			a->unbits=a->quant=0;
		}
	}
	else if(b<=(a->quant))
	{
		for(i=0;i<b;i++) mask=(mask<<1)+1;
		mask=mask<<((a->quant)-b);
		read_bits=((a->unbits)&mask)>>(a->quant)-b;
		a->unbits=(a->unbits)-((a->unbits)&mask);
		a->quant=(a->quant)-b;
	}
	return read_bits;
}

int main()
{
	int bits;
	FILE *ff;
	ff=fopen("frames.txt","r");
	unread *inf;
	inf->unbits=0;
	inf->quant=0;
	bits=get_bit(ff,inf,8);
	printf("%d %d %d\n",bits,inf->unbits,inf->quant);
	bits=get_bit(ff,inf,9);
	printf("%d %d %d\n",bits,inf->unbits,inf->quant);
	//bits=get_bit(ff,inf,8);
	//printf("%d %d %d\n",bits,inf->unbits,inf->quant);
	fclose(ff);	
}
